package org.vt.eldercare.console;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.vt.eldercare.ElderCareGUI;

public class ConsoleWindow extends JPanel {

	private static final long serialVersionUID = -8129589823459139645L;
	private JTextArea textArea = new JTextArea(15, 30);
	private TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
			textArea);
	private static PrintStream oldOut = System.out;
	private static ElderCareGUI parent = null;

	public static void setParent(ElderCareGUI parent) {
		ConsoleWindow.parent = parent;
	}

	public ConsoleWindow() {
		setLayout(new BorderLayout());
		add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
		System.setOut(new PrintStream(taOutputStream));
	}

	public static JFrame create() {
		JFrame frame = new JFrame("Console");
		frame.getContentPane().add(new ConsoleWindow());
		frame.pack();
		Dimension d = new Dimension();
		d.setSize(800, 400);
		frame.setMinimumSize(d);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		frame.addWindowListener(new ConsoleCloseHandler());
		return frame;
	}

	private static class ConsoleCloseHandler extends WindowAdapter {
		public void windowClosing(WindowEvent evt) {
			System.setOut(oldOut);
			if(parent != null){
				parent.setConsoleOpen(false);
			}
		}
	}

}
